<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>OpenSearch RAG 多轮对话应用</title>
    <link href="https://unpkg.com/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
    <link rel="preload" href="https://unpkg.com/tailwindcss@2.2.19/dist/tailwind.min.css" as="style">
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
    <style>
        /* 基础样式 */
        body {
            background-color: #f3f4f6;
            margin: 0;
            padding: 0;
            font-family: system-ui, -apple-system, sans-serif;
        }
        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 1rem;
        }
        textarea, button, input {
            font-family: inherit;
        }
        .hidden {
            display: none;
        }
        /* 思考过程折叠区域样式 */
        .thinking-details summary {
            list-style: none;
            position: relative;
            padding-left: 1.5rem;
        }
        .thinking-details summary::-webkit-details-marker {
            display: none;
        }
        .thinking-details summary::before {
            content: '▶';
            position: absolute;
            left: 0;
            transform: translateY(-2px);
            transition: transform 0.2s;
        }
        .thinking-details[open] summary::before {
            transform: rotate(90deg) translateX(-2px);
        }
        /* 对话气泡样式 */
        .chat-bubble {
            border-radius: 1rem;
            padding: 1rem;
            margin-bottom: 1rem;
            max-width: 80%;
        }
        .user-bubble {
            background-color: #e9f5ff;
            margin-left: auto;
            border-top-right-radius: 0.25rem;
        }
        .ai-bubble {
            background-color: #f0f0f0;
            margin-right: auto;
            border-top-left-radius: 0.25rem;
        }
        /* AI气泡中的思考过程样式 */
        .ai-bubble .thinking-details summary {
            list-style: none;
            position: relative;
            padding-left: 1.5rem;
        }
        .ai-bubble .thinking-details summary::-webkit-details-marker {
            display: none;
        }
        .ai-bubble .thinking-details summary::before {
            content: '▶';
            position: absolute;
            left: 0;
            transform: translateY(-2px);
            transition: transform 0.2s;
        }
        .ai-bubble .thinking-details[open] summary::before {
            transform: rotate(90deg) translateX(-2px);
        }
        /* 滚动区域样式 */
        .chat-history {
            height: calc(100vh - 280px);
            overflow-y: auto;
            padding-right: 0.5rem;
        }
        .chat-history::-webkit-scrollbar {
            width: 6px;
        }
        .chat-history::-webkit-scrollbar-track {
            background: #f1f1f1;
        }
        .chat-history::-webkit-scrollbar-thumb {
            background: #c1c1c1;
            border-radius: 3px;
        }
        .chat-history::-webkit-scrollbar-thumb:hover {
            background: #a1a1a1;
        }
    </style>
</head>
<body class="bg-gray-100 min-h-screen">
    <div class="container mx-auto px-4 py-4">
        <h1 class="text-2xl font-bold text-center mb-6 text-gray-800">OpenSearch RAG 多轮对话应用</h1>
        
        <div class="flex flex-col md:flex-row gap-6">
            <!-- 左侧对话历史区域 -->
            <div class="w-full md:w-1/2 bg-white rounded-lg shadow-md p-4 flex flex-col">
                <h2 class="text-xl font-semibold mb-3 text-gray-800">对话历史</h2>
                <div id="chatHistory" class="chat-history mb-4">
                    <!-- 对话历史将在这里动态显示 -->
                </div>
                
                <div class="mt-auto">
                    <textarea 
                        id="searchInput" 
                        class="w-full px-4 py-3 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 resize-none"
                        rows="3"
                        placeholder="请输入您的问题..."
                    ></textarea>
                    <div class="flex justify-between mt-3">
                        <button onclick="clearChat()" 
                                class="px-4 py-2 bg-gray-500 text-white rounded-lg hover:bg-gray-600 focus:outline-none focus:ring-2 focus:ring-gray-500">
                            清空对话
                        </button>
                        <button onclick="search()" 
                                class="px-6 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500">
                            发送
                        </button>
                    </div>
                </div>
            </div>
            
            <!-- 右侧内容区域 -->
            <div class="w-full md:w-1/2 flex flex-col gap-6">
                <!-- 文件上传部分 -->
                <div class="bg-white rounded-lg shadow-md p-4">
                    <h2 class="text-xl font-semibold mb-3 text-gray-800">上传文档</h2>
                    <div class="flex flex-col gap-3">
                        <div class="flex items-center gap-3">
                            <input type="file" 
                                   id="fileInput" 
                                   class="hidden" 
                                   accept=".txt,.pdf,.doc,.docx">
                            <button onclick="document.getElementById('fileInput').click()" 
                                    class="px-3 py-1 bg-gray-500 text-white rounded-lg hover:bg-gray-600 focus:outline-none focus:ring-2 focus:ring-gray-500">
                                选择文件
                            </button>
                            <span id="fileName" class="text-gray-600 text-sm">未选择文件</span>
                        </div>
                        <div class="flex justify-between">
                            <button onclick="uploadFile()" 
                                    id="uploadButton"
                                    class="px-4 py-1 bg-green-500 text-white rounded-lg hover:bg-green-600 focus:outline-none focus:ring-2 focus:ring-green-500 disabled:opacity-50 disabled:cursor-not-allowed"
                                    disabled>
                                上传文档
                            </button>
                            <div id="uploadStatus" class="text-sm"></div>
                        </div>
                    </div>
                </div>

                <!-- 当前回答区域 -->
                <div id="currentAnswer" class="bg-white rounded-lg shadow-md p-4 flex-grow">
                    <h2 class="text-xl font-semibold mb-3 text-gray-800">当前回答</h2>
                    <div id="thinking" class="hidden">
                        <details class="thinking-details mb-4">
                            <summary class="text-lg font-medium text-yellow-800 cursor-pointer hover:text-yellow-600">
                                AI 思考过程 (点击展开/折叠)
                            </summary>
                            <div id="thinkingContent" class="text-gray-700 whitespace-pre-wrap prose mt-3 pl-2 border-l-2 border-yellow-300">
                            </div>
                        </details>
                    </div>
                    
                    <div id="answer" class="hidden">
                        <h3 class="text-lg font-medium mb-2 text-green-600">AI 回答</h3>
                        <div id="answerContent" class="text-gray-700 prose mb-4"></div>
                    </div>
                    
                    <div id="references">
                        <h3 class="text-lg font-medium mb-2 text-gray-800">参考文档</h3>
                        <div id="referencesContent" class="text-gray-500 text-left">
                            尚无参考文档
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div id="loading" class="hidden fixed inset-0 bg-black bg-opacity-30 flex items-center justify-center z-50">
            <div class="bg-white p-6 rounded-lg shadow-xl flex flex-col items-center">
                <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500"></div>
                <p class="mt-4 text-gray-700">处理中，请稍候...</p>
            </div>
        </div>
    </div>

    <script>
        // 存储对话历史
        let chatMessages = [];
        
        // 将函数定义移到全局作用域
        async function uploadFile() {
            const fileInput = document.getElementById('fileInput');
            const uploadStatus = document.getElementById('uploadStatus');
            const uploadButton = document.getElementById('uploadButton');
            
            if (!fileInput.files.length) return;
            
            const formData = new FormData();
            formData.append('file', fileInput.files[0]);
            
            uploadButton.disabled = true;
            uploadStatus.innerHTML = '<div class="text-blue-500">文档上传处理中...</div>';
            
            try {
                const response = await fetch('/upload', {
                    method: 'POST',
                    body: formData
                });
                
                const data = await response.json();
                
                if (data.success) {
                    uploadStatus.innerHTML = `<div class="text-green-500">${data.message}</div>`;
                    fileInput.value = '';
                    document.getElementById('fileName').textContent = '未选择文件';
                } else {
                    uploadStatus.innerHTML = `<div class="text-red-500">上传失败: ${data.error}</div>`;
                }
            } catch (error) {
                uploadStatus.innerHTML = `<div class="text-red-500">上传出错: ${error.message}</div>`;
            } finally {
                uploadButton.disabled = false;
            }
        }

        async function search() {
            const query = document.getElementById('searchInput').value;
            if (!query.trim()) return;

            const loading = document.getElementById('loading');
            
            // 添加用户消息到对话历史
            addMessageToChat('user', query);
            
            // 清空输入框
            document.getElementById('searchInput').value = '';
            
            // 显示加载状态
            loading.classList.remove('hidden');

            try {
                const response = await fetch('/search', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json; charset=utf-8'
                    },
                    body: JSON.stringify({ query })
                });

                const data = await response.json();
                
                // 确保正确解析中文字符
                if (data.success) {
                    // 构建AI回答，包含可折叠的思考过程
                    let aiResponse = data.answer;
                    
                    // 如果有思考过程，添加可折叠的思考部分
                    if (data.thinking) {
                        aiResponse = `
                            <details class="thinking-details mb-2">
                                <summary class="text-sm font-medium text-yellow-800 cursor-pointer hover:text-yellow-600">
                                    查看AI思考过程
                                </summary>
                                <div class="text-gray-700 whitespace-pre-wrap text-sm mt-2 pl-2 border-l-2 border-yellow-300">
                                    ${data.thinking}
                                </div>
                            </details>
                            <div>${data.answer}</div>
                        `;
                    }
                    
                    // 添加AI回答到对话历史
                    addMessageToChat('ai', aiResponse);
                    
                    // 更新右侧当前回答区域
                    updateCurrentAnswer(data);
                } else {
                    // 添加错误消息到对话历史
                    addMessageToChat('ai', `抱歉，处理您的问题时出错: ${data.error}`);
                }
            } catch (error) {
                addMessageToChat('ai', `抱歉，请求失败: ${error.message}`);
            } finally {
                loading.classList.add('hidden');
            }
        }
        
        function addMessageToChat(role, content) {
            // 添加消息到内存中的对话历史
            chatMessages.push({ role, content });
            
            // 创建新的消息元素
            const messageDiv = document.createElement('div');
            messageDiv.className = `chat-bubble ${role === 'user' ? 'user-bubble' : 'ai-bubble'}`;
            
            // 如果是AI回答，检查是否有思考过程
            if (role === 'ai') {
                messageDiv.innerHTML = content;
            } else {
                messageDiv.textContent = content;
            }
            
            // 添加到聊天历史区域
            const chatHistory = document.getElementById('chatHistory');
            chatHistory.appendChild(messageDiv);
            
            // 滚动到底部
            chatHistory.scrollTop = chatHistory.scrollHeight;
        }
        
        function updateCurrentAnswer(data) {
            // 更新思考过程
            const thinking = document.getElementById('thinking');
            const thinkingContent = document.getElementById('thinkingContent');
            
            if (data.thinking) {
                thinking.classList.remove('hidden');
                thinkingContent.textContent = data.thinking;
            } else {
                thinking.classList.add('hidden');
            }
            
            // 更新回答
            const answer = document.getElementById('answer');
            const answerContent = document.getElementById('answerContent');
            
            if (data.answer) {
                answer.classList.remove('hidden');
                answerContent.textContent = data.answer;
            } else {
                answer.classList.add('hidden');
            }
            
            // 更新参考文档
            const referencesContent = document.getElementById('referencesContent');
            
            if (data.results && data.results.length > 0) {
                let referencesHtml = '';
                
                data.results.forEach(result => {
                    referencesHtml += `
                        <div class="mb-3 p-3 bg-gray-50 rounded">
                            <div class="text-gray-600">${result.text}</div>
                            <div class="mt-1 text-xs text-gray-500">相关度: ${Math.round(result.score * 100)}%</div>
                        </div>
                    `;
                });
                
                referencesContent.innerHTML = referencesHtml;
            } else {
                referencesContent.innerHTML = '<div class="text-gray-500 text-left">未找到相关参考文档</div>';
            }
        }
        
        function clearChat() {
            // 清空对话历史
            chatMessages = [];
            document.getElementById('chatHistory').innerHTML = '';
            
            // 清空当前回答区域
            document.getElementById('thinking').classList.add('hidden');
            document.getElementById('answer').classList.add('hidden');
            document.getElementById('referencesContent').innerHTML = '<div class="text-gray-500 text-left">尚无参考文档</div>';
        }

        // DOM 加载完成后的初始化代码
        document.addEventListener('DOMContentLoaded', function() {
            // 文件上传相关的事件监听
            document.getElementById('fileInput').addEventListener('change', function(e) {
                const fileName = e.target.files[0]?.name || '未选择文件';
                document.getElementById('fileName').textContent = fileName;
                document.getElementById('uploadButton').disabled = !e.target.files.length;
            });

            // 添加回车键搜索功能
            document.getElementById('searchInput').addEventListener('keypress', function(e) {
                if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault(); // 阻止默认的换行行为
                    search();
                }
            });
        });
    </script>
</body>
</html>
